package com.example.qu_tao.View;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.qu_tao.R;

public class ZhuXiaoFuWuActivity extends AppCompatActivity {

    private CheckBox cbAgree;
    private Button btnApplyCancel;
    private ImageView ivBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuxiaofuwu);

        cbAgree = findViewById(R.id.cb_agree);
        btnApplyCancel = findViewById(R.id.btn_apply_cancel);
        ivBack = findViewById(R.id.ivBack);

        btnApplyCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbAgree.isChecked()) {
                    // 获取当前用户的 ID
                    long userId = getUserId();
                    if (userId != -1) {
                        // 调用删除用户的方法
                        if (deleteUser(userId)) {
                            // 清除用户信息
                            clearUserId();
                            // 跳转到登录页面
                            Intent intent = new Intent(ZhuXiaoFuWuActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(ZhuXiaoFuWuActivity.this, "注销失败，请稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(ZhuXiaoFuWuActivity.this, "未获取到用户信息", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(ZhuXiaoFuWuActivity.this, "请先勾选同意注销须知", Toast.LENGTH_SHORT).show();
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 实现返回上一个页面的功能
                finish();
            }
        });
    }
    private long getUserId() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        return sharedPreferences.getLong("user_id", -1);
    }

    private boolean deleteUser(long userId) {
        Uri uri = Uri.parse("content://com.example.qu_tao.provider/user/" + userId);
        int rowsDeleted = getContentResolver().delete(uri, null, null);
        return rowsDeleted > 0;
    }

    private void clearUserId() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove("user_id");
        editor.apply();
    }
}
